/**
 * 验证手机验证码
 */
/* eslint-disable @typescript-eslint/no-var-requires */
import { opType } from './../../../const/index';
import { getUserInfo } from '../../../model/service/account/userInfo';
const codeUtil = require('../../../util/code/codeUtil');

/**
 * type 0 -- 注册， 1 -- 登录, 2 -- 修改东西
 */

export default async function verifyCode(ctx: Context, next: Next): Promise<void> {
  const { body } = ctx.request;
  const { phoneNumber, code, type } = body

  const isCorrect = codeUtil.verifyCode(phoneNumber, code);

  // 验证码不正确
  if (!isCorrect) { 
    ctx.api.fail(-1, '验证码错误');
    return next();
  }

  // 注册
  if (Number(type) === opType.register || Number(type) === opType.modify) {
    ctx.api.success({}, 'sucess');
  } else if (Number(type) === opType.login) {
    // 登录验证码正确直接返回用户数据就好了
    const result = await getUserInfo({ phoneNumber });
    ctx.api.success(result, 'sucess');
  } else {
    ctx.api.fail(-1, '接口错误');
  }

  return next();
}